package kuzha.runtime.jadapter;

import java.lang.reflect.Array;
import java.util.AbstractList;

import kuzha.KuzhaObject;
import kuzha.Utils;
import kuzha.runtime.Converter;

public class FromArrayAdapter extends AbstractList<KuzhaObject> implements FromJavaObjectAdapter {
	private final Object array;
	
	public FromArrayAdapter(Object array) {
		if (array == null || !array.getClass().isArray())
			throw new IllegalArgumentException();
		this.array = array;
	}
	
	@Override
	public KuzhaObject get(int index) {
		return Converter.toKuzhaObject(Array.get(array, index));
	}
	
	@Override
	public KuzhaObject set(int index, KuzhaObject element) {
		KuzhaObject before = Converter.toKuzhaObject(Array.get(array, index));
		Array.set(array, index, Converter.cast(array.getClass().getComponentType(), element));
		return before;
	}
	
	@Override
	public int size() {
		return Array.getLength(array);
	}
	
	@Override
	public String toString() {
		return "[" + Utils.join(" ", array) + "]";
	}
	
	@Override
	public Object toJavaObject() {
		return array;
	}
}
